package com.yswy.app.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserAgreementQueryRequest;
import com.alipay.api.response.AlipayUserAgreementQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yswy.common.vo.dto.PayOrderVo;
import com.yswy.common.vo.dto.RetuenPayOrderVo;
import com.yswy.app.service.*;
import com.yswy.common.model.ResultModel;
import com.yswy.common.utils.UserLockUtils;
import com.yswy.common.zfbOrder.CallbackAgreementResVO;
import com.yswy.domain.common.BasePojo;
import com.yswy.domain.entity.AgreementOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;

import static com.yswy.domain.common.util.TokenUtils.getIP;
import static com.yswy.domain.common.util.TokenUtils.getUserId;

@RestController
@RequestMapping("/payOrder")
@Api(description = "订单")
@Slf4j
public class PayOrderController {
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private PayOrderZfbLogService payOrderZfbLogService;
    @Autowired
    private AgreementOrderService agreementOrderService;
    @Autowired
    private AgreementOrderPayLogService agreementOrderPayLogService;
    @Autowired
    private TgChannleService tgChannleService;
    @Autowired
    private PayOrderWxLogService payOrderWxLogService;
    /** 下单接口 **/
    @PostMapping("/addOrder")
    @ApiOperation(value = "下单接口")
    public ResultModel addPayOrder(@RequestBody() PayOrderVo payOrderVo
            , HttpServletRequest request) {
        synchronized (UserLockUtils.getLock("addOrderUserId:"+getUserId(request))){
            long begin = System.currentTimeMillis();
            log.info(payOrderVo.toString());
            RetuenPayOrderVo retuenPayOrderVo = payOrderService.addPayOrder(payOrderVo , getUserId(request) , getIP(request) );
            long end = System.currentTimeMillis();
            log.info("耗时：tg/handleCallback："+ (end-begin));
            return ResultModel.ok(retuenPayOrderVo);
        }
    }


    /** 查询订单详情 **/
    @GetMapping("/selectOrderState")
    @ApiOperation(value = "查询订单状态")
    public ResultModel selectPayOrder(@RequestParam(value = "payOrderId") String payOrderId
            , HttpServletRequest request) {
        return ResultModel.ok(payOrderService.checkingPayOrder(payOrderId , getUserId(request) ));
    }


    /** 支付宝回调接口 **/
    @PostMapping("/callbackOrder")
    @ApiOperation(value = "支付宝回调接口")
    public void callbackPayOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            payOrderZfbLogService.callbackPayOrder(request , response);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("success");
            response.getWriter().flush();
            response.getWriter().close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /** 支付宝业务失败手动回调接口 **/
    @GetMapping("/callbackZfbYwPayOrder")
    @ApiOperation(value = "支付宝业务失败手动回调接口")
    public ResultModel callbackZfbYwPayOrder(@RequestParam(value = "payOrderId") String payOrderId) {
        payOrderZfbLogService.callbackZfbYwPayOrder(payOrderId);
        return ResultModel.ok();
    }
    /** 微信业务失败手动回调接口 **/
    @GetMapping("/callbackWXYwPayOrder")
    @ApiOperation(value = "微信业务失败手动回调接口")
    public ResultModel callbackWXYwPayOrder(@RequestParam(value = "payOrderId") String payOrderId) {
        payOrderWxLogService.callbackWXYwPayOrder(payOrderId);
        return ResultModel.ok();
    }

    @PostMapping("/callbackAgreement")
    @ApiOperation(value = "周期付款回调接口")
    public void callbackAgreement(HttpServletRequest request, HttpServletResponse response) {
        try {
            agreementOrderService.callbackAgreement(request , response);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("success");
            response.getWriter().flush();
            response.getWriter().close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


//    @GetMapping("/testIs1111")
//    @ApiOperation(value = "测试扣量")
    public Boolean testIs1111() {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(
                    "https://openapi.alipay.com/gateway.do"
                    ,"2021004116687081",
                    "MIIEvw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WV3EECgYEAp9NWn8nO04s9rC0vCGkosjDS2K/ED5b6b5OCzhRzSFkvmFrNRXKPt74YIeWWdqlWXuIyTF6KDyvMy1G3YiBhmvIfnkknk9oqxHaG+tfFol8d2hZ2daww6ypQZKm5Do0ws58DJ98Pw6N5UjjS2VGrak+bBuWPSHtGs21C7g65tRECgYBhNKsprmDmywgNC62NG1iE++DChHqor4E6NfIYKMtZsIBhr6IEj4OLYKw9egW4CGkNinkDXngn/y0QgmGLGrQPzZPesRAA/I+Otp9GLK0UET+T8YK/c8xzqo5/aKc1syUu9a9cyhoSuB358bvLSIrxOPx2174V23mV5K7f4jJ/AQKBgQCCg8VDqwzkX4fgKRt8n6kiWV9kFlacOlDMsBFukf0WEUt+Vfyw/tqhn86a7c+JOUU2YV/AK4rGGgmZVgVZCZegko5b3qXm6MOUNmIllZnA6MQaEUWIsZfrYfNaDl7NReVxyRVvVAGqUKZ7KeoXbncekonwTI9tTUnz8TotsiIxkQ==",
                    "json",
                    "UTF-8",
                    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk2gwPKQeax1WHEbOSq3b+ogwI9yFt1uJI+q/Aku9iCrvG2G06Cx9jTJ/7lIiMlRTODQZSfbDTnP/p2vXobJWILFd94k4ZnoHOf9bVP2w7Bo3V8jSFm18nZrWwC+X9aqIMEGKp1DoCk/Nu5GRz9EBh5CA64sUCx9LaJNIVjXkhpQBaqrN+sgoajp/JaiUbjwpyFnwCfCKPLV2mTO45LH+ZSD8EAYpAvPJf6IC6yVw/7yvmU1D6CuJaCxwtScYKYiFub4zVW+4MLu1AR/QtcwgQy3IKWh7RWDTjuw4ELAFWxzjbpfv3hbjyqYVt8rR000V0co9nEhH0zEJ0sX2kT8h9wIDAQAB",
                    "RSA2");

            List<String> list = new ArrayList<>();

            list.add("zq202310141923003279949824");
            list.add("zq202310141919172353008640");
            List<AgreementOrder>  agreementOrders = agreementOrderService.list(
                    new LambdaQueryWrapper<AgreementOrder>().ge(BasePojo::getId , 7550)
                            .eq(AgreementOrder::getStatus , 0));
            List<AgreementOrder>  agreementOrders1 = new ArrayList<>();
            for (AgreementOrder s:agreementOrders){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                AlipayUserAgreementQueryRequest request = new AlipayUserAgreementQueryRequest();
                com.alibaba.fastjson.JSONObject qryBizContent = new com.alibaba.fastjson.JSONObject();
//        协议产品码personal_product_code + sign_scene + external_agreement_no
                qryBizContent.put("personal_product_code" ,"CYCLE_PAY_AUTH_P");
                //用户的支付宝账号对应 的支付宝唯一用户号
//        qryBizContent.put("alipay_user_id" ,"2088732548124550");
                //用户的支付宝登录账号，支持邮箱或手机号码格式
//        qryBizContent.put("alipay_logon_id" ,alipay_logon_id);
                //签约场景码
                qryBizContent.put("sign_scene" ,"INDUSTRY|DEFAULT_SCENE");
                //代扣协议中标示用户的唯一签约号
                qryBizContent.put("external_agreement_no" ,s.getExternalAgreementNo());
                //签约第三方主体类型。对于三方协议，表示当前用户和哪一类的第三方主体进行签约。取值范围: 1. PARTNER（平台商户）; 2. MERCHANT（集团商户），集团下子商户可共享用户签约内容;
//        qryBizContent.put("third_party_type" ,"PARTNER");
                //支付宝系统中用以唯一标识用户签约记录的编号
//            qryBizContent.put("agreement_no" ,s);
                System.out.println(qryBizContent.toString());
                request.setBizContent(qryBizContent.toString());
                AlipayUserAgreementQueryResponse response = null;
                try {
                    response = alipayClient.execute(request);
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                if(response.isSuccess()){
                    System.out.println(response);
                    System.out.println(response.getStatus());
                    if (response.getStatus() .equals("NORMAL")){
                        CallbackAgreementResVO callbackAgreementResVO = new CallbackAgreementResVO(response);



                        agreementOrderService.userAgreementOk(callbackAgreementResVO);
                        System.out.println("调用成功"+callbackAgreementResVO.getExternal_agreement_no());
                    }



                } else {
//                    System.out.println(response.toString());
                    System.out.println("调用失败");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            return null ;
        }
        return null;
    }





    @PostMapping("/zfbCallback")
    @ApiOperation(value = "应用网关地址")
    public void zfbCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            agreementOrderService.zfbCallback(request , response);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("success");
            response.getWriter().flush();
            response.getWriter().close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /** 微信回调接口 **/
    @PostMapping("/wechatPayNotify")
    @ApiOperation(value = "微信回调接口")
    public String wechatPayNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            return payOrderWxLogService.callbackWXPayOrder(request , response);
        }catch (Exception e){
            e.printStackTrace();
            return null ;
        }
    }

//
//
//    @ApiOperation("微信退款回调接口")
//    @PostMapping("/wx/refund/callback")
//    public String refundWechatCallback(HttpServletRequest request, HttpServletResponse response) {
//        return WxPayCallbackUtil.wxPayRefundCallback(request, response, verifier, wxPayConfig, new WechatRefundCallback() {
//            @Override
//            public void success(WxchatCallbackRefundData refundData) {
//                // TODO 退款成功的业务逻辑，例如更改订单状态为退款成功等
//            }
//
//            @Override
//            public void fail(WxchatCallbackRefundData refundData) {
//                // TODO 特殊情况下退款失败业务处理，例如银行卡冻结需要人工退款，此时可以邮件或短信提醒管理员，并携带退款单号等关键信息
//            }
//        });
//
//    }


    @GetMapping("/testIsDeduction")
    @ApiOperation(value = "测试扣量")
    public Boolean testIsDeduction(@RequestParam(value = "channle") String channle) {
        try {
            Boolean isDeduction = tgChannleService.isDeduction(channle , 100);
            return isDeduction;
        }catch (Exception e){
            e.printStackTrace();
            return null ;
        }
    }

    @GetMapping("/testPayAgreement")
    @ApiOperation(value = "测试拉起周期付款")
    public String testPayAgreement(@RequestParam(value = "payOrderId") Long payOrderId) {
        try {
            payOrderService.test(payOrderId);
            return "cg";
        }catch (Exception e){
            e.printStackTrace();
            return "sb" ;
        }
    }

    @GetMapping("/userAgreementUpdateExTime")
    @ApiOperation(value = "延期接口")
    public Boolean userAgreementUpdateExTime(@RequestParam(value = "memo") String memo,
                                             @RequestParam(value = "deduct_time") String deduct_time,
                                             @RequestParam(value = "agreement_no") String agreement_no) {
        try {
            agreementOrderService.userAgreementUpdateExTime(memo , deduct_time , agreement_no);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false ;
        }
    }


}
